﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EmptyStringToNullableIntConverter.cs" company="XamlmNinja">
//   2010
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Communications.PropertySearch.Resources
{
    using System;
    using Newtonsoft.Json;

    public sealed class EmptyStringToNullableIntConverter : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return null;

            int result;
            if (int.TryParse(reader.Value.ToString(), out result))
            {
                return result;
            }
            return existingValue;
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(int?).IsAssignableFrom(objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}